package com.dailyblue.java.project.smbms.users.interceptor;

import com.alibaba.fastjson.JSONArray;
import com.dailyblue.java.spring.project.smbms.commons.config.JwtConfig;
import com.dailyblue.java.spring.project.smbms.commons.config.ResultCode;
import com.dailyblue.java.spring.project.smbms.commons.config.ResultTool;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class IskLoginInterceptor implements HandlerInterceptor {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        System.out.println("接收到token:" + token);
        if (token == null) {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(JSONArray.toJSONString(ResultTool.fail(ResultCode.USER_NOT_LOGIN)));
            return false;
        }
        Claims claims = JwtConfig.parseJWT(token);
        System.out.println("Claims:" + claims);
        int id = (int) claims.get("id");
        System.out.println("id:" + id);
        ValueOperations<String, String> value = redisTemplate.opsForValue();
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setValueSerializer(stringSerializer);
        String result = value.get("token:" + id);
        System.out.println("result:" + result);
        if (result == null) {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(JSONArray.toJSONString(ResultTool.fail(ResultCode.USER_NOT_LOGIN)));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
/*
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJkYWlseWJsdWUiLCJpYXQiOjE2NjI1MjEzNzEsImV4cCI6MTY2MjYwNzc3MSwiaWQiOjEsIm5hbWUiOiLns7vnu5_nrqHnkIblkZgifQ.xE8lKpM5FJ9tG63ILEE_dzjVs7QWQKd4DzbgD83X6QM
*/